// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import {HttpResponse} from '@/types/axios'
const showStatus = (status: number) => {
  let message = "";
  switch (status) {
    case 400:
      message = "请求错误(400)";
      break;
    case 401:
      message = "未授权，请重新登录(401)";
      break;
    case 403:
      message = "拒绝访问(403)";
      break;
    case 404:
      message = "请求出错(404)";
      break;
    case 408:
      message = "请求超时(408)";
      break;
    case 500:
      message = "服务器错误(500)";
      break;
    case 501:
      message = "服务未实现(501)";
      break;
    case 502:
      message = "网络错误(502)";
      break;
    case 503:
      message = "服务不可用(503)";
      break;
    case 504:
      message = "网络超时(504)";
      break;
    case 505:
      message = "HTTP版本不受支持(505)";
      break;
    default:
      message = `连接出错(${status})!`;
  }
  return `${message}，请检查网络或联系管理员！`;
};


const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL,
  timeout: 30000,
});

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // config.headers.Authorization=localStorage.getItem("token")
    return config;
  },
  (error) => {
    // 错误抛到业务代码
    error.data = {};
    error.data.msg = "服务器异常，请联系管理员！";
    return Promise.resolve(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse):any => {
    if (response.data.Ret !== 200) {
      const msg = showStatus(response.data.Ret)
    //   ElMessage.error(msg)
    }

    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 导出get请求方法
 * @url 请求地址
 * @params get请求参数
 */
export const get = (url: string, params: any):Promise<HttpResponse> => {
  return service.get(url, { params });
};

/**
 * 导出post请求方法
 * @url 请求地址
 * @params post请求参数
 */
export const post = (url: string, params: any):Promise<HttpResponse> => {
  return service.post(url, params);
};

// export default service;
